package com.example.module_live


import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.example.lib_common.utils.LoggerUtils
import com.example.lib_common.websocket.ReceiverMsgListener
import com.example.lib_common.websocket.WebSocketUtils
import com.hyphenate.EMMessageListener
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.tencent.live2.V2TXLivePlayer
import com.tencent.live2.impl.V2TXLivePlayerImpl
import com.tencent.rtmp.ui.TXCloudVideoView
import okhttp3.Call
import okhttp3.Callback
import okhttp3.FormBody
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import org.java_websocket.handshake.ServerHandshake
import java.io.IOException


/**
 * 直播间页面
 * 1:拉流
 * 2:访问服务器接口加入直播间后再websocket实时监听
 *
 */
class LiveActivity : AppCompatActivity() {
    ///liveRoom/websocket/{roomId}/{userId}
    private var websocket_url = "10.161.19.229:8887/liveRoom/websocket"
    private var roomId:String = "275183664431108"
    private var userId:String = "caiyilin"
    private var token:String = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJjYWl5aWxpbiIsImV4cCI6MTc0MTkyMzU3NH0.xVrRl7q5Qn7UBZL6JtjuH6inHX8_2pDGHfCYKMCJ7pE"



    var msgListener: EMMessageListener = object : EMMessageListener {
        // 收到消息，遍历消息队列，解析和显示。
        override fun onMessageReceived(messages: List<EMMessage>) {
            //判断消息的类型 文本、礼物
            LoggerUtils.d("LiveActivity", "环信接受的消息:${messages.size}")

        }

        override fun onCmdMessageReceived(messages: MutableList<EMMessage>?) {
            //判断消息的类型 文本、礼物
            LoggerUtils.d("LiveActivity", "环信接受的消息:${messages?.size}")
        }

        override fun onMessageRead(messages: MutableList<EMMessage>?) {
            LoggerUtils.d("LiveActivity", "环信接受的消息:${messages?.size}")

        }

        override fun onMessageDelivered(messages: MutableList<EMMessage>?) {
            LoggerUtils.d("LiveActivity", "环信接受的消息:${messages?.size}")

        }

        override fun onMessageRecalled(messages: MutableList<EMMessage>?) {
            LoggerUtils.d("LiveActivity", "环信接受的消息:${messages?.size}")

        }

        override fun onMessageChanged(message: EMMessage?, change: Any?) {
            //判断消息的类型 文本、礼物
            LoggerUtils.d("LiveActivity", "环信接受的消息:${message}")
        }
    }

    private lateinit var webSocketUtils: WebSocketUtils
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_live)
//        <uses-permission android:name="android.permission.INTERNET" />
//        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
//        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
//        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
//        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
//        <uses-permission android:name="android.permission.RECORD_AUDIO" />
//        <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
//        <uses-permission android:name="android.permission.BLUETOOTH" />
//        <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <!-- IM SDK required start -->
//        <!-- 允许程序振动，用于本地通知设置振动 -->
//        <uses-permission android:name="android.permission.VIBRATE" /> <!-- 访问网络权限 -->
//        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
//        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 允许程序在手机屏幕关闭后后台进程仍然运行 -->
//        <uses-permission android:name="android.permission.WAKE_LOCK" /> <!-- 申请闹钟定时权限，SDK 心跳中使用，3.9.8及以后版本可以不添加 -->
//        <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
        //动态权限
        val permissions = arrayOf(
            "android.permission.INTERNET",
            "android.permission.ACCESS_NETWORK_STATE",
            "android.permission.ACCESS_WIFI_STATE",
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.RECORD_AUDIO",
            "android.permission.MODIFY_AUDIO_SETTINGS",
            "android.permission.BLUETOOTH",
            "android.permission.READ_PHONE_STATE",
            "android.permission.VIBRATE",
            "android.permission.ACCESS_FINE_LOCATION",
            "android.permission.ACCESS_COARSE_LOCATION"
            , "android.permission.WAKE_LOCK", "android.permission.SCHEDULE_EXACT_ALARM"
            , "android.permission.BLUETOOTH_ADMIN"
        )
        requestPermissions(permissions, 100)
        //1:拉流
        playVideo()
        //2:访问服务器接口加入直播间
        val formBody = FormBody.Builder()
            .add("roomId", "275183664431108")
            .build()
        val client = OkHttpClient.Builder()
            .build()
        val request = Request.Builder()
            .url("http://10.161.19.229:8887/liveRoom/enterLiveRoom")
            //aa用户
//            .header("token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhYSIsImV4cCI6MTc0MTkyMDQyMn0.og6r-VJyreIU390Qz4kegfkhtdIL2NvqxTtnz-p8k_g")
            .header("token",token)

            .post(formBody)
            .build();
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                LoggerUtils.d("LiveActivity", "onFailure:${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                LoggerUtils.d("LiveActivity", "onResponse:${response.body?.string()}")
                //3:websocket实时监听
                runOnUiThread {
                    initWebSocket()
                }

            }

        })




    }


    private fun initWebSocket() {
        webSocketUtils = WebSocketUtils.Builder()
            .setWebsocketUrl("$websocket_url/$roomId/$userId")
            .setReceiverMsgListener(object : ReceiverMsgListener {
                override fun onOpen(handshakedata: ServerHandshake?) {
                    LoggerUtils.d("LiveActivity", "onOpen:")
                }

                override fun onMessage(message: String?) {
                    LoggerUtils.d("LiveActivity", "websocket接受到的消息:$message")
                }

                override fun onClose(code: Int, reason: String?, remote: Boolean) {
                    LoggerUtils.d("LiveActivity", "onClose:")
                }

                override fun onError(ex: Exception?) {
                    LoggerUtils.d("LiveActivity", "onError ${ex?.message}:")

                }

            })
            .build()
    }

    private fun playVideo() {
        //mPlayerView 即 step3 中添加的界面 view
//创建 player 对象
        val mLivePlayer: V2TXLivePlayer = V2TXLivePlayerImpl(this)
//关键 player 对象与界面 view
        mLivePlayer.setRenderView(findViewById<TXCloudVideoView>(R.id.video_view))
        val flvUrl = "http://2157.liveplay.myqcloud.com/live/2157_xxxx.flv"
        mLivePlayer.startLivePlay(flvUrl)
    }

    override fun onDestroy() {
        super.onDestroy()
        webSocketUtils.disconnectWs()
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
    }

    fun sendMessage(view: View) {
        val json = "{\"message\": \"你好吗\",\"room_id\": \"275183664431108\"}"
        val requestBody = json.toRequestBody("application/json".toMediaType())


        val client = OkHttpClient.Builder()
            .build()
        val request = Request.Builder()
            .url("http://10.161.19.229:8887/liveRoom/sendMessage")
            //aa用户
//            .header("token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhYSIsImV4cCI6MTc0MTkyMDQyMn0.og6r-VJyreIU390Qz4kegfkhtdIL2NvqxTtnz-p8k_g")
            .header("token",token)
            .post(requestBody)
            .build();
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                LoggerUtils.d("LiveActivity", "onFailure:${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                LoggerUtils.d("LiveActivity", "发送消息:${response.body?.string()}")

            }

        })

    }
    fun sendGift(view: View) {
        val json = "{\"giftId\": 3,\"room_id\": \"275183664431108\"}"
        val requestBody = json.toRequestBody("application/json".toMediaType())


        val client = OkHttpClient.Builder()
            .build()
        val request = Request.Builder()
            .url("http://10.161.19.229:8887/liveRoom/sendGift")
            //aa用户
//            .header("token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhYSIsImV4cCI6MTc0MTkyMDQyMn0.og6r-VJyreIU390Qz4kegfkhtdIL2NvqxTtnz-p8k_g")
            .header("token",token)
            .post(requestBody)
            .build();
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                LoggerUtils.d("LiveActivity", "onFailure:${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                LoggerUtils.d("LiveActivity", "发送礼物:${response.body?.string()}")

            }

        })
    }
    fun getGiftList(view: View) {
        val client = OkHttpClient.Builder()
            .build()
        val request = Request.Builder()
            .url("http://10.161.19.229:8887/gift/getGiftList")
            //aa用户
//            .header("token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhYSIsImV4cCI6MTc0MTkyMDQyMn0.og6r-VJyreIU390Qz4kegfkhtdIL2NvqxTtnz-p8k_g")
            .header("token",token)
            .build();
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                LoggerUtils.d("LiveActivity", "onFailure:${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                LoggerUtils.d("LiveActivity", "礼物列表:${response.body?.string()}")

            }

        })
    }
}